package com.aipodcast.webbackend.utils;

import com.aipodcast.webbackend.config.OssConfig;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;

/**
 * @author RedStar
 * @Date 2025/09/25
 * @Description
 */
@Component
public class OssUtil {

    @Resource
    private OssConfig ossConfig;

//    public OssUtil() {
//        this.ossConfig = new OssConfig();
//        ossConfig.setEndpoint("https://oss-cn-hangzhou.aliyuncs.com");
//        ossConfig.setAccessKeyId("LTAI5tLKE9w7DudBSawceMuX");
//        ossConfig.setAccessKeySecret("GRxp6Vn3Spiwoqi0BcYbUdyMus8bUh");
//        ossConfig.setBucketName("xm-note");
//    }

    public String getSignUrl(String fileName){
        // 以华东1（杭州）的外网Endpoint为例
        String endpoint = ossConfig.getEndpoint();

        // 使用固定的 AccessKeyId 和 AccessKeySecret（建议后续放到配置中心或环境变量中）
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        // 填写Bucket名称
        String bucketName = ossConfig.getBucketName();
        // 这里用参数传进来的文件名，而不是写死
        String objectName = fileName;

        // 创建OSSClient实例（默认就是 V1 签名）
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        URL signedUrl = null;
        try {
            // 过期时间 1 小时
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);

            // 生成预签名 URL，使用 PUT 上传
            GeneratePresignedUrlRequest request =
                    new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);

            request.setExpiration(expiration);

            // 可选：设置 Content-Type，避免前端与签名不一致
            request.setContentType("video/mp4");

            signedUrl = ossClient.generatePresignedUrl(request);

            System.out.println("signed url for putObject: " + signedUrl);

        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
        } catch (ClientException ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return signedUrl != null ? signedUrl.toString() : null;
    }

    public String uploadFile(InputStream inputStream, String fileName) throws IOException {
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );
        try {
            // 上传文件
            ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream);
            return getFileUrl(fileName);
        } finally {
            ossClient.shutdown();
        }
    }

    public String getFileUrl(String fileName) {
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint().replace("https://", "") + "/" + fileName;
    }

    public static void main(String[] args) {
        String signUrl = new OssUtil().getSignUrl("exampleobject.txt");
        System.out.println(signUrl);
    }
}
